<template>
  <view class="viewport">
    <wd-navbar
      :bordered="false"
      placeholder
      safeAreaInsetTop
      left-arrow
      custom-style="background-color:#92beab;"
      custom-class="color:#fff"
    >
      <template #title>
        <view class="custom-title-style">详情页面</view>
      </template>
      <template #capsule>
        <wd-navbar-capsule @back="handleBack" @back-home="handleBackHome" />
      </template>
    </wd-navbar>
  </view>
  <view class="clothes-detail">
    <!-- 主图片 -->
    <image
      :src="getFullImagePath(form.imageUrl)"
      mode="aspectFit"
      class="clothes-image"
    />
    <view class="info-box">
      <text class="clothes-name">名称：{{ form.name }}</text>
      <text class="clothes-desc">描述：{{ form.description }}</text>
      <text class="clothes-category">分类：{{ form.categoryName }}</text>
      <text class="clothes-season">季节：{{ form.season }}</text>
    </view>

    <view class="sell-switch">
      <text class="label">是否售卖：</text>
      <switch
        :checked="isSell"
        style="transform: scale(0.7)"
        @change="toggleSell"
      />
    </view>
    <view v-if="isSell && form.statusSale === '0'" class="sell-extra">
      <view class="price-input">
        <input
          type="number"
          v-model="form.price"
          placeholder="请输入售卖价格"
          class="input-box"
        />
        <input
          type="number"
          v-model="form.size"
          placeholder="请输入尺寸大小"
          class="input-box"
        />
        <textarea
          v-model="form.introduce"
          placeholder="请输入搭配描述"
          maxlength="300"
          class="textarea"
        ></textarea>
      </view>
      <view class="form-item">
        <text class="label">搭配图片</text>
        <view class="image-list">
          <view
            class="image-item"
            v-for="(img, index) in form.images"
            :key="index"
          >
            <image :src="img" mode="aspectFill" class="image" />
            <view class="delete-btn" @click="removeImage(index)">×</view>
          </view>
          <view class="upload-btn" @click="chooseImage">
            <uni-icons type="plus" size="16" color="#92beab"></uni-icons>
          </view>
        </view>
      </view>
      <button type="primary" class="sell-btn" @click="handleSell">
        确认挂售
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { getCategoryAPI, getClothesDetailAPI } from "@/api/clothes";
import { onLoad } from "@dcloudio/uni-app";
import { avatarUrlImg } from "@/api/config/http";
import { postGoodsAPI } from "@/api/goods";

const isSell = ref(false);
const baseImageUrl = avatarUrlImg;
const categoryMap = ref<Record<number, string>>({});
// 获取完整图片路径
const getFullImagePath = (path: string | undefined) => {
  if (!path) return ""; // 或者返回默认图片路径
  return path.startsWith("http") ? path : baseImageUrl + path;
};
const form = reactive({
  clothesId: "",
  introduce: "",
  name: "",
  imageUrl: "",
  description: "",
  images: [] as string[],
  season: "",
  category: "",
  statusSale: "",
  price: "",
  categoryName: "",
  size: "",
});
// 切换是否挂售
const toggleSell = (e: any) => {
  if (form.statusSale === "1") {
    uni.showToast({ title: "该衣物已挂售", icon: "none" });
  }
  isSell.value = e.detail.value;
};

// 删除图片
const removeImage = (index: number) => {
  form.images.splice(index, 1);
};

const chooseImage = () => {
  uni.chooseImage({
    count: 6, // 最多选择 6 张
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    quality: 70, // 压缩质量 0-100
    success: (res) => {
      if (Array.isArray(res.tempFilePaths)) {
        res.tempFilePaths.forEach((p: string, i: number) => console.log(i, p));
        const newImages = [...form.images, ...res.tempFilePaths].slice(0, 6);
        form.images = newImages;
      } else if (typeof res.tempFilePaths === "string") {
        const newImages = [...form.images, res.tempFilePaths].slice(0, 6);
        form.images = newImages;
      }
    },
    fail: (err) => {
      console.error("选择图片失败:", err);
    },
  });
};

// 确认挂售
const handleSell = async () => {
  if (!form.price) {
    uni.showToast({ title: "请输入价格", icon: "none" });
    return;
  }
  if (!form.size) {
    uni.showToast({ title: "大小", icon: "none" });
    return;
  }
  // 价格必须为数字（整数或小数）
  if (!/^\d+(\.\d+)?$/.test(form.price)) {
    uni.showToast({ title: "价格必须是数字", icon: "none" });
    return;
  }
  if (form.images.length === 0) {
    uni.showToast({ title: "请上传售卖图片", icon: "none" });
    return;
  }

  const uploadPromises = form.images.map((filePath) => {
    return uni.uploadFile({
      url: "/match/uploadImages",
      filePath,
      name: "files",
      method: "POST",
    });
  });
  const resArr = await Promise.all(uploadPromises);
  const idImage: any = [];
  resArr.forEach(async (res) => {
    const data = JSON.parse(res.data);
    if (data.code === 200 || data.code === "200") {
      idImage.push(...data.data);
    } else {
      console.warn("上传失败", data.msg);
    }
  });

  if (idImage.length === form.images.length) {
    const Goodsimage = [form.imageUrl, ...idImage].filter(Boolean);
    const params = {
      clothesId: form.clothesId,
      category: form.category,
      name: form.name,
      description: form.description,
      introduce: form.introduce,
      size: form.size,
      price: form.price,
      imageUrls: Goodsimage,
      season: form.season,
      statusSale: "1",
    };
    try {
      const res: any = await postGoodsAPI(params);
      if (res.code === "200") {
        uni.showToast({ title: "发布成功", icon: "success" });
        isSell.value = false;
      }
    } catch (error) {
      form.statusSale = "0";
    }
  }
  // 后续改成调用后端 API
  // uni.showToast({ title: "保存成功", icon: "success" });
  // setTimeout(() => {
  //   uni.navigateBack();
  // }, 1000);
};

const getCategory = async () => {
  const res: any = await getCategoryAPI();
  if (res.code === "200") {
    // 直接赋值
    categoryMap.value = res.data || {};
  }
};
const handleBack = () => {
  uni.navigateBack({});
};
const handleBackHome = () => {
  uni.reLaunch({
    url: "/pages/index/index",
  });
};
// 页面加载获取衣物详情
onLoad(async (options: any) => {
  const id = options.id;
  // 先获取分类映射
  await getCategory();
  // 再获取衣物详情
  const res: any = await getClothesDetailAPI(id);
  if (res.code === "200") {
    const data = res.data;
    form.clothesId = data.id;
    form.imageUrl = data.imageUrl;
    form.name = data.name;
    form.description = data.description;
    form.season = data.season;
    form.category = data.category;
    form.statusSale = data.statusSale;
    form.categoryName = categoryMap.value[data.category];
    // 开关默认状态
    isSell.value = form.statusSale === "1" || form.statusSale === "0";
    // 如果已挂售，直接提示，不能编辑
    if (form.statusSale === "1") {
      isSell.value = true; // 开关显示为开
    } else {
      isSell.value = false; // 默认关闭
    }
  }
});
</script>

<style lang="scss">
.clothes-detail {
  padding: 16px;
}
.clothes-image {
  width: 100%;
  height: 300px;
  margin-bottom: 10px;
  border-radius: 8px;
}
.info-box {
  margin-bottom: 20px;
  .clothes-name {
    display: block;
    height: 60rpx;
    font-size: 18px;
    font-weight: bold;
  }
  .clothes-desc {
    display: block;
    height: 60rpx;
    font-size: 18px;
  }
  .clothes-category,
  .clothes-season {
    height: 60rpx;
    display: block;
    margin-top: 2px;
    font-size: 14px;
    color: #999;
  }
}

.textarea {
  display: flex;
  margin: 20rpx 0;
  width: 100%;
  background: #fff;
  padding: 20rpx 10rpx;
  border-radius: 8rpx;
  border: 1rpx solid #ddd;
  // padding: 16rpx;
  font-size: 28rpx;
}
.sell-switch {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .label {
    margin-right: 8px;
  }
}

.sell-extra {
  margin-bottom: 20px;
  .price-input {
    margin-bottom: 20px;
    .input-box {
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 6px;
    }
  }
}
.sell-btn {
  background-color: #007aff;
  color: white;
}

.form-item {
  margin: 0 20rpx;
  margin-bottom: 24rpx;
  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: flex;
  }
  .input,
  .textarea {
    display: flex;
    width: 100%;
    background: #fff;
    border-radius: 8rpx;
    border: 1rpx solid #ddd;
    padding: 16rpx;
    font-size: 28rpx;
  }
  .textarea {
    min-height: 120rpx;
  }
  .input {
    height: 60rpx;
  }
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;

  .image-item {
    position: relative;
    .image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
    }
    .delete-btn {
      position: absolute;
      top: -12rpx;
      right: -12rpx;
      background: rgba(0, 0, 0, 0.6);
      color: #fff;
      border-radius: 50%;
      width: 36rpx;
      height: 36rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
    }
  }

  .upload-btn {
    width: 160rpx;
    height: 160rpx;
    background: #fff;
    border: 2rpx dashed #92beab;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
